<title>选课搜索</title>

<div class="layui-card layadmin-header">
    <div class="layui-breadcrumb" lay-filter="breadcrumb">
        <a><cite>选课</cite></a>
        <a><cite>专业课</cite></a>
    </div>
</div>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header" id="layui-card-header">专业课</div>
                <div class="layui-card-body">
                    <div class="layui-form">
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">专业</label>
                            <div class="layui-input-inline" style="width: 75px;margin-left: 10px;float: left;">
                                <select lay-filter="yearFilter" id="yearFilter" name="yearFilter">
                                </select>
                            </div>
                            <div class="layui-input-inline" style="width: 155px;margin-left: 10px;float: left;">
                                <select lay-filter="specialtyFilter" id="specialtyFilter" name="specialtyFilter">
                                </select>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">课程</label>
                            <div class="layui-input-block" id="class-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">教师</label>
                            <div class="layui-input-block" lay-filter="teacher" id="teacher-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;">时间</label>
                            <div class="layui-input-block" id="time-radio" style="margin-left: 60px">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label" style="width: 28px; margin-left: 0px;"></label>
                            <button class="layui-btn layui-btn-sm" lay-submit lay-filter="submit">确认</button>
                            <button id="screening" class="layui-btn layui-btn-sm" lay-submit lay-filter="screening">筛除</button>
                            <button id="refreshBtn" class="layui-btn layui-btn-sm" lay-submit lay-filter="refresh">重选</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">人数显示</div>
                <div class="layui-card-body">
                    <div class="layui-carousel layadmin-carousel layadmin-dataview">
                        <div style="width: 100%; height:300px" id="LAY-index-dataview">
                        </div>
                    </div>
                </div>
            </div>
            <div class="layui-card">
                <div class="layui-card-header">课程列表</div>
                <div class="layui-card-body">
                    <table class="layui-hide" id="test-table-page" lay-filter="test"></table>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/html" id="lineBar">
    <a class="layui-btn layui-btn-xs" lay-event="detail">选课页</a>
</script>
<script src="/js/controller/textSort.js"></script>
<script>
    layui.use(['jquery', 'table', "echarts", "carousel", "table"], function(){
        var $ = layui.$, form = layui.form,
            echarts = layui.echarts, admin = layui.admin,
            view = layui.view, table = layui.table;

        var host = "";
        var stuGrade;
        var stuSpecialtyCode;
        var classInfoData;              // 存放课程信息
        var radioIdMap = {};            // radio id记录
        var selClassInfoIndexList = [];
        var radioId = 0;
        var year_list = [];         // 记录年份列表
        var specialty_list = [];    // 记录专业列表
        var tableln;

       // 获取学生的专业、年级信息
        var load = layer.load(2);
       $.ajax({
           url: host + "/jw/stu/info",
           dataType: 'JSON',
           complete: function (result) {
               layer.close(load);
               result = result.responseJSON;
               if (result['status'] !== 200) {
                   layer.msg(result.message)
               } else {
                   var data = result['data'];
                   stuGrade= data['grade'];
                   stuSpecialtyCode = data['specialtyCode'];
                   renderGrade(stuGrade);
                   renderSpecialty(stuGrade);
                   renderCourseList(stuGrade, stuSpecialtyCode)
                   // 隐藏重选按钮
                   $('#refreshBtn').hide();
               }
           }
       });

        // 渲染年份
        function renderGrade(grade) {
            grade = parseInt(grade);
            var today = new Date();
            var year = today.getFullYear();
            var startYear = year - 4;
            for (var i = year; i >= startYear; i--) {
                if (i === grade) {
                    $('#yearFilter').append("<option value='" + i + "' selected>" + i + "</option>");
                }else {
                    $('#yearFilter').append("<option value='" + i + "'>" + i + "</option>");
                }
                year_list.push(i);
            }
            form.render("select")
       }

       // 渲染专业
       function renderSpecialty(grade) {
            $.ajax({
                url: host + "/jw/specialty/" + grade,
                dataType: 'JSON',
                complete: function (result) {
                    result = result.responseJSON;
                    if (result['status'] === 200) {
                        // 清空
                        $('#specialtyFilter').empty();

                        var list = result.data;
                        specialty_list = [];
                        var html = "<option value=''>请选择专业</option>";
                        $('#specialtyFilter').append(html);
                        for(var specialty in list) {
                            specialty = list[specialty];
                            specialty_list.push(specialty);
                            var specialtyName = specialty['name'];
                            if (specialtyName.length > 13) {
                                specialtyName = specialtyName.substr(0, 13) + ".."
                            }
                            if (specialty['code'] === stuSpecialtyCode) {
                                html = "<option selected value='" + specialty['code'] + "'>" + specialtyName + "</option>"
                            } else  {
                                html = "<option value='" + specialty['code'] + "'>" + specialtyName + "</option>"
                            }
                            $('#specialtyFilter').append(html);
                        }
                        form.render("select");
                    } else {
                        layer.msg(result['message'])
                    }
                }
            })
       }

       function renderCourseList(grade, specialtyCode) {
            $.ajax({
                url: host + "/jw/course/specialty/" + grade + "/" + specialtyCode,
                dataType: 'JSON',
                complete: function (result) {
                    result = result.responseJSON;
                    if (result['status'] === 200) {
                        classInfoData = result['data'];
                        renderRadio();
                        renderTable(classInfoData);
                    }else {
                        layer.msg(result['message'])
                    }
                }
            });
       }

        function renderRadio() {
            // 清理工作
            $('#class-radio').empty();
            $('#teacher-radio').empty();
            $('#time-radio').empty();
            radioIdMap = {};
            radioId = 0;

            // 添加数据
            var data = [];
            if (selClassInfoIndexList.length === 0)  {
                data = classInfoData;
            }else {
                for (var i = 0; i < selClassInfoIndexList.length; i++) {
                    data.push(classInfoData[selClassInfoIndexList[i]]);
                }
            }
            var classNameSet = new Set();
            var teacherSet = new Set();
            var timeSet = new Set();

            for(var index in data) {
                var oneClass = data[index];
                var className = oneClass.className;
                classNameSet.add(className);
                var teacher = oneClass.teachers.toString();
                teacherSet.add(teacher);
                var timeList = [];
                oneClass.time.forEach(function (value) {
                    timeList.push(value.description);
                });
                var time = timeList.toString();
                timeSet.add(time);
            }
            timeSet = new Set(Array.from(timeSet).sort(sortText));
            teacherSet = new Set(Array.from(teacherSet).sort(sortText));
            classNameSet = new Set(Array.from(classNameSet).sort(sortText));

            for (var campus of classNameSet) {
                addRadio("class-radio", "className", campus, classNameSet.size === 1);
            }
            for (var teacher of teacherSet) {
                addRadio("teacher-radio", "teacher", teacher, teacherSet.size === 1);
            }
            for (var time of timeSet) {
                addRadio("time-radio", "time", time, timeSet.size === 1);
            }
            form.render();
            // 人数显示
            if (selClassInfoIndexList.length === 0) {
                var classIndexList = [];
                for (var i = 0; i < classInfoData.length; i++) {
                    classIndexList.push(i);
                }
                drawPersonNum(classIndexList);
            }else {
                drawPersonNum(selClassInfoIndexList);
            }
        }

        // 数组变为字符串
        function strs2Str(strs) {
            var s = "";
            for (var i = 0; i < strs.length; i++) {
                var str = strs[i];
                if(i < strs.length - 1) {
                    s += (str + ",")
                } else {
                    s += str
                }
            }
            return s;
        }

        function list2Str(list, key) {
            var str = "";
            var set = new Set();
            for(var i = 0; i < list.length; i++) {
                set.add(list[i][key])
            }
            set.forEach(function (data) {
                str += data + " "
            });
            return str;
        }

        function addRadio(id, name, value, checked) {
            radioIdMap[value] = "radio-" + radioId++;
            var title = value;
            if (title.length > 23) title = title.substring(0, 21) + "..";
            var html = "<input type='radio' lay-filter='filter' name=" + name + " value='" + value + "' title='" + title + "' id='" + radioIdMap[value]  + "'";
            if (checked){
                html += " checked>";
            }else {
                html += ">";
            }
            $('#' + id).append(html);
        }

        // 人数画图
        function drawPersonNum(classinfoIndexs) {
            var classlist = [];
            var limitNums = [];
            var nowNums = [];
            var determineNums = [];
            classinfoIndexs.forEach(function (index) {
                var timeList = [];
                classInfoData[index].time.forEach(function (value) {
                    timeList.push(value.description);
                });
                classlist.push(classInfoData[index].className + "." + classInfoData[index].teachers.toString() + "--" + timeList.toString())
                limitNums.push(classInfoData[index].limitNum);
                nowNums.push(classInfoData[index].nowNum);
                determineNums.push(classInfoData[index].determineNum);
            });

            // 根据数量和宽度判断变成折线图还是柱状图
            var width = window.screen.availWidth;
            var type = "line";
            if (classinfoIndexs.length <= 8 && width > 800) {
                type = "bar";
            }


            // 是否有滑动条,以及显示多少数据
            var len = 100;
            var slide = false;
            if (classinfoIndexs.length >= 20 || width < 1000) {
                slide = true;
                var num = parseInt(width / 100 * 1.2);
                len = parseInt(num / classinfoIndexs.length * 100);
            }

            if (classinfoIndexs.length === 1) {
                type = "bar";
                slide = false;
            }
            var personData = {
                title: {
                    text: '专业课人数',
                    textAlign: "auto",
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function(data)
                    {
                        var teacher = data[0].name.split(".")[1].split("--")[0] + "</br>";

                        var timeStart = data[0].name.indexOf("--");
                        var time = data[0].name.substr(timeStart + 2);
                        var timeList = time.split(",");
                        var timeDescription = "";
                        timeList.forEach(function (time) {
                            timeDescription += time + "</br>";
                        });

                        var personDescription = "";
                        data.forEach(function (classData) {
                            personDescription += classData.seriesName + "：" + classData.data + "</br>"
                        });

                        return teacher + timeDescription + personDescription;
                    }
                },
                legend: {
                    type: "scroll",
                    data: ["限选", "已选", "确定"]
                },
                xAxis: [{
                    type: "category",
                    boundaryGap: true,
                    axisLabel : {
                        interval:0,
                        rotate:20,
                        formatter : function(params){
                            var index = params.indexOf("--");
                            var str = params.substr(0, index);
                            if (str.length > 11) {
                                return str.substr(0, 10) + ".."
                            }
                            return str;
                        }

                    },
                    data: classlist
                }],
                yAxis: [{
                    type: "value"
                }],
                series: [{
                    name: "限选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: limitNums
                }, {
                    name: "已选",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: nowNums
                },{
                    name: "确定",
                    type: type,
                    barMaxWidth:30,
                    smooth: !0,
                    itemStyle: {
                        normal: {
                            areaStyle: {
                                type: "default"
                            }
                        }
                    },
                    data: determineNums
                }],
                dataZoom:{
                    type: 'slider',
                    show: slide,
                    height:10,//滚动条高度
                    start:0,//滚动条开始位置（共100等份）
                    end: len//结束位置（共100等份）
                }
            };
            var card= document.getElementById('LAY-index-dataview');
            var myChart = echarts.init(card, layui.echartsTheme);
            myChart.setOption(personData);
            myChart.resize();
        }

        // 监听radio
        form.on('radio(filter)', function(data){
            // 显示重选按钮
            $('#refreshBtn').show();

            var sel_className = $("input[name='className']:checked").val();
            var sel_teacher = $("input[name='teacher']:checked").val();
            var sel_time = $("input[name='time']:checked").val();
            selClassInfoIndexList = [];
            var selClassInfoList = [];

            for (var index in classInfoData) {
                var oneClass = classInfoData[index];
                if (sel_className == null || sel_className === oneClass.className) {
                    if (sel_teacher == null || sel_teacher === oneClass.teachers.toString()) {
                        var timeList = [];
                        oneClass.time.forEach(function (value) {
                            timeList.push(value.description);
                        });
                        if (sel_time == null || sel_time === timeList.toString()) {
                            selClassInfoIndexList.push(index);
                            selClassInfoList.push(classInfoData[index]);
                        }
                    }
                }
            }
            renderTable(selClassInfoList);
            renderRadio();
        });

        // 监听确认按钮
        form.on("submit(submit)", function () {
            if ( selClassInfoIndexList.length !== 1) {
                layer.msg("请选择");
                return;
            }
            var data = classInfoData[selClassInfoIndexList[0]];
            var defaultWidth = 420;
            var defaultHeight = 700;
            var width = window.screen.availWidth;
            var height = window.screen.availHeight;
            if (width < 1000) defaultWidth = width;
            if (height < 1000) defaultHeight = height * 0.9;
            admin.popup({
                title: "选课",
                area: [defaultWidth + "px", defaultHeight + "px"],
                id: "LAY-popup-user-elective-confirm",
                success: function(layero, index) {
                    data['teacher'] = data['teachers'].toString();
                    var remark = "";
                    var timeList = data.time;
                    layui.each(timeList, function (index, item) {
                        remark += item.description;
                        if(item.classRoom.toString() !== "") {
                            remark += "-" + item.classRoom.toString();
                        }
                        if (item.remark !== "") {
                            remark += "-" + item.remark;
                        }
                        remark += "<br>";
                    });
                    data['remark'] = remark;
                    view(this.id).render("menu/elective/confirmClass", data).done(function () {
                        form.on("submit(LAY-user-back-submit)",function (formData) {
                            layer.close(index);
                            var load = layer.load(2);
                            var field = formData.field;
                            var content = {};
                            content['classCode'] = data.classCode;
                            content['classNum'] = data.classNum;
                            content['coin'] = $('#coinDiv')[0].textContent;
                            content['buy'] = field.hasOwnProperty("buy");
                            content['retake'] = field.hasOwnProperty("retake");
                            content['adjust'] = field.hasOwnProperty("adjust");
                            $.ajax({
                                url: host + '/jw/stu/course/elective/save',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(content),
                                dataType: 'json',
                                complete: function (result) {
                                    result = result.responseJSON;
                                    if (result.status === 200) {
                                        layer.msg("选课成功");
                                        layui.sessionData("stuCourse", null);
                                    }else {
                                        layer.msg(result.message);
                                    }
                                    layer.close(load);
                                }
                            })
                        });
                    });
                }
            });
        });

        // 监听重选按钮
        form.on("submit(refresh)", function (data) {
            selClassInfoIndexList = [];
            renderRadio();
            // 隐藏按钮
            $('#refreshBtn').hide();
            form.render();
            renderTable(classInfoData);
        });

        function transCourseTimeList(courseList) {
            var result = [];
            for (var i = 0; i < courseList.length; i++) {
                var courseTimes = [];
                for (var j = 0; j < courseList[i]["time"].length; j++) {
                    courseTimes.push(courseList[i]["time"][j])
                }
                result.push(courseTimes)
            }
            return result;
        }
        function checkTimeConflict(courseTime, stuCourseTimeList) {
            for (var i = 0; i < stuCourseTimeList.length; i++) {
                var weeks = courseTime["weeks"];
                for (var j = 0; j < weeks.length; j++) {
                    var anotherWeek = stuCourseTimeList[i]["weeks"];
                    if (anotherWeek.includes(weeks[j])) {
                        if (courseTime["day"] === stuCourseTimeList[i]["day"]) {
                            var lesson = courseTime["lesson"];
                            for (var k = 0; k < lesson.length; k++) {
                                if (stuCourseTimeList[i]["lesson"].includes(lesson[k])) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
        function getTimeConflict(stuCourseList, courseList) {
            var stuCourseTimeList = [];
            for (var i = 0; i < stuCourseList.length; i++) {
                for (var j = 0; j < stuCourseList[i]["time"].length; j++) {
                    stuCourseTimeList.push(stuCourseList[i]["time"][j])
                }
            }
            var courseTimeList = transCourseTimeList(courseList);
            var result = [];
            for (i = 0; i < courseTimeList.length; i++) {
                var add = false;
                for (j = 0; j < courseTimeList[i].length; j++) {
                    var conflict = checkTimeConflict(courseTimeList[i][j], stuCourseTimeList);
                    if (conflict) {
                        result.push(conflict);
                        add = true;
                        break;
                    }
                }
                if (!add) result.push(false)
            }
            return result;
        }
        function getPersonNumConflict(classInfos) {
            var personNumConflict = [];
            for (var i = 0; i< classInfos.length; i++) {
                personNumConflict.push(classInfos[i]["limitNum"] <= classInfos[i]["determineNum"])
            }
            return personNumConflict;
        }
        function getConflictList(stuCourseList, courseList) {
            var timeConflict = getTimeConflict(stuCourseList, courseList);
            var personNumConflict = getPersonNumConflict(courseList);
            var conflictList = [];
            for (var i = 0; i <  courseList.length; i++) {
                conflictList.push(timeConflict[i] || personNumConflict[i])
            }
            return conflictList;
        }


        // 监听筛除按钮
        form.on("submit(screening)", function () {
            var listStr = JSON.stringify(layui.sessionData("stuCourse"));
            if (listStr !== "{}") {
                var stuCourse = JSON.parse(layui.sessionData("stuCourse")['list']);
                afterGetStuCourse(stuCourse);
            }else {
                var load = layer.load(2);
                $.ajax({
                    url: host + "/jw/stu/timetable",
                    dataType: "JSON",
                    complete: function (result) {
                        result = result.responseJSON;
                        if (result["status"] === 200) {
                            layui.sessionData("stuCourse", {key: "list", value: JSON.stringify(result["data"]["courseList"])});
                            afterGetStuCourse(result["data"]["courseList"]);
                            layer.close(load);
                        }
                    }
                })
            }
        });

        function afterGetStuCourse(stuCourse) {
            var conflictList = getConflictList(stuCourse, classInfoData);
            var newClassData = [];
            for(var i = 0; i < classInfoData.length; i++) {
                if (!conflictList[i]) {
                    newClassData.push(classInfoData[i])
                }
            }
            classInfoData = newClassData;
            renderTable(classInfoData);
            renderRadio();
            $('#screening').hide();
            form.render();
        }

        // 监听年份，点击后获取当年的专业列表
        form.on("select(yearFilter)", function () {
            var load = layer.load(2);
            var grade = $('#yearFilter').val();
            var specialtyCode = $('#specialtyFilter').val();
            renderCourseList(grade, specialtyCode);

            // 显示筛除按钮
            $('#screening').show();
            $('#refreshBtn').hide();
            layer.close(load);
        });

        // 监听点击专业
        form.on('select(specialtyFilter)', function () {
            var load = layer.load(2);
            var grade = $('#yearFilter').val();
            var specialtyCode = $('#specialtyFilter').val();
            renderCourseList(grade, specialtyCode);

            // 显示筛除按钮
            $('#screening').show();
            $('#refreshBtn').hide();
            layer.close(load);
        });

        function renderTable(classInfoDataList) {
            if (tableln === undefined) {
                tableln = table.render({
                    elem: '#test-table-page'
                    ,cols:[[
                        {field:'className', width:200, title:'课程', align:'left'}
                        ,{field:'teacher', width:200, title:'教师', align:'left', templet: function (d) { return strs2Str(d['teachers']) }}
                        ,{field:'time', width:320, title:'时间', templet: function (d) {return list2Str(d.time, "description")}}
                        ,{field:'credit', width:60, title:'学分'}
                        ,{field: 'remark', minWidth:200, title:'备注', templet: function (d) { return list2Str(d.time, "remark")}}
                    ]]
                    ,data: classInfoDataList
                    ,limit: classInfoDataList.length
                })
            }else {
                tableln.reload({
                    data: classInfoDataList
                    ,limit: classInfoDataList.length
                })
            }
        }
    });
</script>